package com.worksystem.Common;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;

import com.worksystem.entity.User;

@Component
public class Common{
	@Autowired
	public  HttpServletRequest request;
	@Autowired
	public HttpServletResponse response;
	
	private static JsonConfig jsonConfig ;
	protected static ModelAndView mav=new ModelAndView();
	static{
		jsonConfig= new JsonConfig();
		//将时间格式化
		jsonConfig.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor());
	}
	/**
	 * 过滤json中的参数,并过滤时间
	 * @param object 传递实体进去
	 * @param parameters 需要过滤的参数
	 * @return
	 */
	protected JSONArray processorParameter(Object object,String[] parameters){
		if(parameters!=null){
			jsonConfig.setExcludes(parameters);
		}
		return  JSONArray.fromObject(object,jsonConfig);
	}
	
	/**
	 * 注入网站一直存在的实体对象
	 * @param mv
	 * @return
	 */
	public ModelAndView injectDefaultModel(ModelAndView mv){
		HttpSession session=request.getSession();
		//如果登陆的话，注入在线用户
		if(session.getAttribute("onlineuser")!=null){
			User user=(User) session.getAttribute("onlineuser");
			mv.addObject("user",user);
		}
		return mv;
	}
	/**
	 * 初始化默认的Model
	 */
	public  void initDefaultModel(){
		HttpSession session=request.getSession();
		//如果登陆的话，注入在线用户
		if(session.getAttribute("onlineuser")!=null){
			User user=(User) session.getAttribute("onlineuser");
			mav.addObject("user",user);
		}
	}
	
	public ModelAndView checkpermission(ModelAndView mv){
		HttpSession session=request.getSession();
		if(session.getAttribute("onlineuser")==null){
			mv.setViewName("user/login");
			return mv;
		}
		else{
			return null;
		}
	}
	
	public String writJson(Object object){
		return JSONArray.fromObject(object).toString();
	}
	
	public String writJson(Object object,String... filters){
		return processorParameter(object, filters).toString();
	}
}
